import * as React from 'react';
import classNames from 'classnames';

export interface AvatarProps {
	shape?: 'circle' | 'square';
	children?: React.ReactNode;
	className?: string;
	alt?: string;
	src?: React.ReactNode;
	draggable?: boolean;
	icon?: React.ReactNode;
	size?: 'large' | 'small' | 'default' | number;
	onError?: () => void;
}

const Avatar: React.FC<AvatarProps> = props => {
	const prefixCls = 'bh-avatar';
	const {
		shape,
		children,
		className,
		alt,
		src,
		draggable,
		icon,
		size,
		...restProps
	} = props;

	const hasChildren = !!children;
	let childrenToRender;
	const hasImageElement = React.isValidElement(src);
	const sizeCls = classNames({
		[`${prefixCls}-lg`]: size === 'large',
		[`${prefixCls}-sm`]: size === 'small',
	});
	const classString = classNames(
		prefixCls,
		sizeCls, 
		className,
		{
			[`${prefixCls}-${shape}`]: !!shape,
			[`${prefixCls}-string`]: hasChildren,
		}
	);
	const sizeStyle = typeof size === 'number'
      ? {
          width: size,
          height: size,
          lineHeight: `${size}px`,
          fontSize: icon ? size / 2 : 18,
        }
      : {};
	const handleImgLoadError = () => {
		const { onError } = props;
		const errorFlag = onError ? onError() : undefined;
	};
	if(hasImageElement) {
		childrenToRender = src;
	}else if(typeof src == 'string') {
		childrenToRender = (
			<img src={src} alt={alt} draggable={draggable} onError={handleImgLoadError} />
		);
	}else if(icon) {
		childrenToRender = icon;
	}else {
		childrenToRender = (
			<span className={`${prefixCls}-string`}>{children}</span>
		);
	}

	return (
		<div {...restProps} className={classString} style={{ ...sizeStyle}}>
		    {childrenToRender}
		</div>
	)
};

export default Avatar;